package com.xiaoma.mframe.project.tool.gen.service.Impl;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import com.xiaoma.mframe.general.web.entity.Cache;
import com.xiaoma.mframe.general.utils.Convert;
import com.xiaoma.mframe.general.web.entity.SessionEntity;
import com.xiaoma.mframe.project.tool.gen.entity.User;
import com.xiaoma.mframe.project.tool.gen.mapper.UserMapper;
import com.xiaoma.mframe.project.tool.gen.service.IUserService;

/**
 * 用户 服务层实现
 * 
 * @author machuxin
 * @date 2018-10-26
 */
@Service
public class UserServiceImpl implements IUserService 
{
	@Autowired
	private UserMapper userMapper;


	/**
     * 查询用户信息
     * 
     * @param userId 用户ID
     * @return 用户信息
     */
    @Override
	public User selectUserById(Integer userId)
	{
	    return userMapper.selectUserById(userId);
	}
	
	/**
     * 查询用户列表
     * 
     * @param user 用户信息
     * @return 用户集合
     */
	@Override
	public List<User> selectUserList(User user)
	{
	    return userMapper.selectUserList(user);
	}
	
    /**
     * 新增用户
     * 
     * @param user 用户信息
     * @return 结果
     */
	@Override
	public int insertUser(User user)
	{
		int result = getRandom();

		user.setUserId(result);
	    return userMapper.insertUser(user);
	}
	 /**
     * 随机数生成
     * @return 结果
     */
	private int getRandom() {
		Random random = new Random();
		int result=0;
		for (int i=0;i<20;i++)
		{
			result+=random.nextInt(10);
		}
		return result;
	}
	
	/**
     * 修改用户
     * 
     * @param user 用户信息
     * @return 结果
     */
	@Override
	public int updateUser(User user)
	{
	    return userMapper.updateUser(user);
	}

	/**
     * 删除用户对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteUserByIds(String ids)
	{
		return userMapper.deleteUserByIds(Convert.toStrArray(ids));
	}

	@Override
	public int login(User user, HttpServletRequest request) {
        HttpSession session = request.getSession();
        try {
        	User userTmp = new User();
        	userTmp.setUserId(user.getUserId());
        	userTmp.setPassword(user.getPassword());
	        User userT= userMapper.selectUserByIdAndPassword(userTmp);
	        if(null != userT){
	         //設置緩存項
	        	Cache c =new Cache("userId",userT.getUserId(),180000,false);
	            SessionEntity.putCache("userId", c); 
	            session.setAttribute("userId",userT.getUserId());
	            return 1;
	        }
	        return 0;
        } catch (Exception e){
        	 return 0;
        }
	}
	
}
